package com.hisense.hiioc.hismartplate.server.base;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: almo
 * @Date: 2018/12/5 下午2:07
 * @Version 1.0
 */
public abstract class BaseServer implements IServer {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected DefaultEventLoopGroup defaultEventLoopGroup;
    protected NioEventLoopGroup coreLoopGroup;
    protected NioEventLoopGroup workLoopGroup;
    protected NioServerSocketChannel serverSocketChannel;
    protected ChannelFuture channelFuture;
    protected ServerBootstrap serverBootstrap;

    public void init() {
        defaultEventLoopGroup = new DefaultEventLoopGroup(8, new ThreadFactory() {
            private AtomicInteger index = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "DEFAULT_EVENT_LOOP_GROUP:" + index.incrementAndGet());
            }
        });
        coreLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
            private AtomicInteger index = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "CORE_LOOP_GROUP:" + index.incrementAndGet());
            }
        });
        workLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 10, new ThreadFactory() {
            private AtomicInteger index = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "WORK_LOOP_GROUP:" + index.incrementAndGet());
            }
        });

        serverBootstrap = new ServerBootstrap();
    }

    @Override
    public void shutDown() {
        logger.debug("stop server");
        if (defaultEventLoopGroup != null) {
            defaultEventLoopGroup.shutdownGracefully();
        }
        coreLoopGroup.shutdownGracefully();
        workLoopGroup.shutdownGracefully();
    }

}
